var fieldJobId;
var changeFromClick = false;
// var reBackNodeText;
// 初始化数据
var parameterData = [ {
	valueCode : '0',
	valueName : '默认参数'
}, {
	valueCode : '1',
	valueName : '自定义参数'
} ];
// 定位显示
var arrayLi = [];
var arrayLiInd = 0;

var resultSysNum = 0;
var loadSysNum = 0;
$(document)
		.ready(
				function() {					
					
					// 接口请求参数
					$("#sourceDatagrid").datagrid({
						url : '',
						method:'get',
						autoRowHeight:true,
						singleSelect:true,
						striped:true,
						nowrap:false,
						columns:[[
									{field:'host',title:'主机名称',width:140},
									{field:'port',title:'端口',width:70},
									{field:'isAnonmous',title:'是否匿名',width:100},
									{field:'isDelSourceFile',title:'是否删除源文件',width:115},
									{field:'userName',title:'用户名',width:115},
									{field:'password',title:'密码',width:115}
						      ]]
					});
					
					// 接口返回参数
					$("#desDatagrid").datagrid({
						url : '',
						method:'get',
						autoRowHeight:true,
						singleSelect:true,
						striped:true,
						nowrap:false,
						columns:[[
									{field:'host',title:'主机名称',width:140},
									{field:'port',title:'端口',width:70},
									{field:'isAnonmous',title:'是否匿名',width:100},
									{field:'isCoverFile',title:'是否覆盖目标文件',width:115},
									{field:'userName',title:'用户名',width:115},
									{field:'password',title:'密码',width:115}
						      ]]
					});
					
					$("#requestDatagrid").datagrid({
						url : '',
						method:'get',
						autoRowHeight:true,
						singleSelect:true,
						striped:true,
						nowrap:false,
						columns:[[
									{field:'paramName',title:'参数名称',width:140},
									{field:'paramDataType',title:'参数类型',width:130},
									{field:'isNeed',title:'必填',width:80},
									{field:'paramDefaultValue',title:'默认值',width:100},
									{field:'paramDes',title:'参数描述',width:200}
						      ]]
					});
					
					$("#reponseDatagrid").datagrid({
						url : '',
						method:'get',
						autoRowHeight:true,
						singleSelect:true,
						striped:true,
						nowrap:false,
						columns:[[
									{field:'paramName',title:'参数名称',width:140},
									{field:'paramDataType',title:'参数类型',width:70},
									/* {field:'isNeed',title:'是否必须',width:100}, */
									{field:'paramDes',title:'参数描述',width:115}
						      ]]
					});
					
					
					$(".right_con").css({"display": "block",'height':'auto'});
					$(".right_con_second").css("display", "none");
					
					$("#divDatagrid").show();
					$("#divTextArea").hide();
					$("#ff input").val("");
					$("#ff :input").bind('change', function() {
						$("#ff").data("changed", true);
					});
					// 参数模型下拉框
					$('#comboxParameterModel').combobox({
						valueField : 'valueCode',
						textField : 'valueName',
						editable : false,
						value : "0",
						data : parameterData,
						onSelect : function(record) {
							if ("0" == record.valueCode) {
								$("#divDatagrid").show();
								$("#divTextArea").hide();
							} else {
								$("#divDatagrid").hide();
								$("#divTextArea").show();
							}
						}
					});
					// 领域系统结构树
					var tree_id = '';
					var isSave = false;
					var modifyNode;

					$(".tree_con #tt").tree({						
						url : BASE_URL_TREE
						+ '/findVisibleInterfaces'
						+ '?v=' + Math.random(),
						lines : false,
						onLoadSuccess : function() {
							$("#tt > li > ul > li > .tree-node > .tree-file").css("background","url('../../../images/st_folder.png') 2px 2px no-repeat");
								var nodes = $('#tt').tree('getChildren');
								
								var end = nodes.length > 100? 99:nodes.length;
								changeNodeClass(nodes, 0, end);
						},					
						onBeforeSelect : function(node) {
							if ($(node.target).children(".tree-folder").length) {
								return false;
							}
							if ($(node.target).children("tree-file").length && ($(node.target).parent().parent().parent().parent()[0].id == "tt" || $(node.target).parent().parent()[0].id == "tt")) {
								return false;
							}
							return true;
						},
						onClick : function(node) {
							arrayLi = [];
							arrayLiInd = 0;
							changeFromClick = true;
							$("#systemName").val(node.text);
						},
						onSelect : function(node) {					
							$("#ff").data("changed", false);
							if (node.nodeType == 'systemInterface') {
								// $(".right_mask").css("display","none");
								fieldJobId = node.id;
								if (tree_id != fieldJobId) {
									tree_id = fieldJobId;
									$("#ff input").val("");
								} else {
									return false;
								}
								var interfaceId;
								$.ajax({
											url : BASE_URL_HTTP_INTERFACE + '/findIfByIdForServiceScan' + '?id=' + node.id + '&v=' + Math.random(),
											dataType : 'json',
											type : 'get',
//contentType : "application/json",
											success : function(data) {
												FormEcho(data);
												
											},
											error : function() {
												$.messager
														.alert(
																"错误",
																"<p>服务异常，查询接口信息失败，请重新登录或稍后再试！ </p>",
																"error");
											}

										});

							}						
						}
					});


$("#searchNode").click(function(e) {
	if ($("#systemName").val() != '') {
		//后台查询匹配的接口
		$.ajax({
			url : BASE_URL_HTTP_INTERFACE + '/findHttpInterfaceByIfName' + '?ifName=' + encodeURI($("#systemName").val()) + '&v=' + Math.random(),
			dataType : 'json',
			type : 'get',
			success : function(data) {
				if(data.backValue == true){
					var system = data.httpDatas;
					if(system.indexOf(",") != -1){
						var systems = system.split(",");
					}else{
						var systems = [system];
					}
					resultSysNum = systems.length;
					loadSysNum = 0;
					for(var i=0; i < systems.length; i++){
						//展开系统的节点
						//找到树的所有节点
						var nodes = $('#tt').tree('getChildren');
						for(var j = 0; j < nodes.length; j++)
						{
							if(nodes[j].text == systems[i]){
								var $self = $(nodes[j].target).find("span.tree-fieldSys");
								if($self.length)
								{	
									 expendNode(nodes[j]);
								}
								else
								{
									loadSysNum++;
									if(loadSysNum >= resultSysNum)
									{
										choose_tree();
									}
								}
								break;
							}
						}
						
					}
				
				}else{
					$.messager.alert("错误","<p>没有找到包含  " + $("#systemName").val() + " 的接口！ </p>","error");
				}
			},
			error : function() {
				$.messager.alert("错误","<p>服务异常，查询接口信息失败，请重新登录或稍后再试！ </p>","error");
			}
		});
	} else {
		// 搜索关键字为空时，不进行搜索
		/*
		 * $("input").val(""); var row = $('#tt li .tree-node');
		 * row.removeClass('tree-node-selected');
		 */
		$(".tree_con").scrollTop(0);
	}
});
$("#systemName").bind('input propertychange', function() {
	if (changeFromClick) {
		changeFromClick = false;
		return;
	}
	arrayLi = [];
	arrayLiInd = 0;
	resultSysNum = 0;
	loadSysNum = 0;
	if ($("#systemName").val() != '') {
		//choose_tree();
	} else { // 搜索关键字为空时，不进行搜索
		/*
		 * $("#ff input").val(""); var row = $('#tt li .tree-node');
		 * row.removeClass('tree-node-selected');
		 */
		$(".tree_con").scrollTop(0);
	}
});
$(document, "#systemName").keyup(function(event) {
	if (event.keyCode == 13) {
		$("#searchNode").trigger("click");
	}
});

function expendNode(node) {
	var $self = $(node.target).find("span.tree-collapsed");
	if(!$self.length)
	{
		return;
	}
	$self.removeClass('tree-collapsed').addClass('tree-expanded');
	jsonData = {
			systemId:$self.attr("data-id"),
			ifIds:$self.attr("data-ifIds")
	}
	$.ajax({
		url :BASE_URL_TREE+ '/getHttpBySystemIdForScan',
		dataType : 'json',
		type : 'post',
		data:jsonData,
		success : function(data){
			//alert(data)
			$('#tt').tree('append',{
				parent: $self.parent()[0],
				data: data
			});
			loadSysNum++;
			if(loadSysNum >= resultSysNum)
			{
				choose_tree();
			}
		},
		error: function() {
			loadSysNum++;
			if(loadSysNum >= resultSysNum)
			{
				choose_tree();
			}
		}
	}); 
}

function getSelected() {
	var node = $('#tt').tree('getSelected');
	if (node.nodeType == 'systemInterface') {
		$.ajax({
			url : BASE_URL_BASE_URL_HTTP_INTERFACE_CRUD + '/' + node.id + '?v='
					+ Math.random(),
			dataType : 'json',
			type : 'get',
			contentType : "application/json",
			success : function(data) {
				FormEcho(data);
			},
			error : function() {
				alert("error");
			}

		});
	}
}

function choose_tree() {
	$('#tt').tree('expandAll');
	if (arrayLi.length == 0 && arrayLiInd == 0) {
		var searchVal = $("#systemName").val();
		var row = $('#tt li .tree-node');
		var rowcolumn = $('#tt li .tree-node > .tree-title');
		var i = 0, j = 0;

		// row.removeClass('tree-node-selected');
		row.removeClass('tree-node-hover');
		rowcolumn.each(function(column) {
			var matchVal = $(this).text();
			if (matchVal.indexOf(searchVal) != -1) {
				i++;
				var scrTop = $(".tree_con").scrollTop() + $(this).offset().top
						- parseInt($(".tree_con").css("padding-top"), 10)
						- $(".search-con")[0].offsetHeight
						- $(".left_menu > .menu_tit")[0].offsetHeight;

				if (i <= 1) {
					// $(this).parent().addClass('tree-node-selected');
					$(this).parent().addClass('tree-node-hover'); // 改成鼠标hover状态，不选中搜索结果

					$(".tree_con").scrollTop(scrTop);
					arrayLiInd = 1;
					// getSelected();
				}
				arrayLi.push([ matchVal, scrTop ]);
			}
		});
	} else {
		var rowcolumn = $('#tt li .tree-node > .tree-title');
		var row = $('#tt li .tree-node');
		// row.removeClass('tree-node-selected');
		row.removeClass('tree-node-hover');
		if (arrayLiInd < arrayLi.length) {
			rowcolumn.each(function(column) {
				var matchVal = $(this).text();
				if (matchVal == arrayLi[arrayLiInd][0]) {
					// $(this).parent().addClass('tree-node-selected');
					$(this).parent().addClass('tree-node-hover'); // 改成鼠标hover状态，不选中搜索结果
					$(".tree_con").scrollTop(arrayLi[arrayLiInd][1]);
					arrayLiInd++;
					// getSelected();
					return false;
				}
			});
		} else {
			// arrayLi = [];
			arrayLiInd = 0;
			$(".tree_con").scrollTop(0);
			choose_tree();
		}
	}
}


	showIfDetial();
});

function jumpToSerivceApply(){
	window.parent.OpenTab("服务接入申请","pages/esb/ServiceChannelManagement/serviceAccessApplicationList.html","", true);
}
//表单数据回显
function FormEcho(data) {
	
		if(data.type == "3"){
			$(".right_con").css("display", "none");
			$(".right_con_second").css("display", "block");
			$("#ftpInterfaceInfo").text(data.interfaceName + "-接口基本信息");
			$("#ftpInterfaceDes").text(data.desc);
			if(data.ifPublic == "0"){
				$("#ftpIsPublic").text("私有");
			}else{
				$("#ftpIsPublic").text("公开");
			}
			
			if(data.isSchedule == "0"){
				$(".startData").css("display", "none");
				$(".endData").css("display", "none");
				$("#sheduleCys").text("外部调用地址：");
				$("#shedulCycs").text(data.ifScheduleDatas[0].scheduleDescription);
			}else{
				$("#shedulBeginTime").text(data.ifScheduleDatas[0].beginTime);
				$("#shedulEndTime").text(data.ifScheduleDatas[0].endTime);
				$("#shedulCycs").text(data.ifScheduleDatas[0].scheduleDescription);
			}
			
			
			var sourceData = {
				total:"",
				rows:data.FtpJsonSourceDatas
			};
			$("#sourceDatagrid").datagrid('loadData', sourceData);
			
			var desData = {
				total:"",
				rows:data.FtpJsonDesDatas
			};
			$("#desDatagrid").datagrid('loadData', desData);
			  
			
		}else{
			$(".right_con").css("display", "block");
			$(".right_con_second").css("display", "none");
			var reqRows = $(".add").find("tr").size();
			for(var i = reqRows; i >　1; i--){
				$(".add").find("tr").eq(i - 1).remove();
			}
			
			var repRows = $(".add_rep").find("tr").size();
			for(var j = repRows; j >　1; j--){
				$(".add_rep").find("tr").eq(j - 1).remove();
			}
			
			
			$("#interfaceInfo").text(data.name + "-接口基本信息");
			
			// alert(JSON.stringify(data));
			$("#interfaceDes").text(data.desc);
			$("#interfaceAddress").text(data.pubUrl);
			if(data.type == "1"){
				$("#requestMethod").text("POST");
				if(data.contentType == "0"){
					$("#contentType").text("text/xml; charset=utf-8");
				}else{
					$("#contentType").text("application/soap+xml; charset=utf-8");
				}
				$("#soapActionUri").text(data.soapActionUri);
				$(".soapAction").css("display", "block");
			}else{
				$(".soapAction").css("display", "none");
			}
			
			
			
			if(data.authType == "0"){
				$("#interfaceAuthorMode").text("免认证");
			}else if(data.authType == "1"){
				$("#interfaceAuthorMode").text("Http-Basic-Key");
			}else if(data.authType === "2"){
				$("#interfaceAuthorMode").text("Oauth认证");
			}else{
				$("#interfaceAuthorMode").text("WS-Security");
			}
			
			$("#callToken").text(data.accessToken);
			if(data.ifPublic == "0"){
				$("#isPublic").text("私有");
			}else{
				$("#isPublic").text("公开");
			}
			
			if(data.type == "1"){
				$("#req_param").css("display", "block");
			}else{
				$("#req_param").css("display", "none");
			}
			
			
			if(data.requestMess != null && data.requestMess != ""){
				$("#requestParametersMsg").text(data.requestMess.replace(/&lt;/g, "<").replace(/&gt;/g, ">"));
			}
			
			if(data.returnMess != null && data.returnMess != ""){
				$("#responesParametersMsg").text(data.returnMess.replace(/&lt;/g, "<").replace(/&gt;/g, ">"));
			}
			
			var requestParams = {
					total:"",
					rows:data.IfParameterReqJsonDatas
			}
			$("#requestDatagrid").datagrid('loadData', requestParams);
			
			var reponseParams = {
					total:"",
					rows:data.IfParameterRepJsonDatas
			}
			$("#reponseDatagrid").datagrid('loadData', reponseParams);
			
			if($("#requestParametersTable").height() - 6 > 150){
				$("#requestParametersMsg").height($("#requestParametersTable").height() - 6);
			}else{
				$("#requestParametersMsg").height(150);
			}
			
			if($("#reponseParametersTable").height() - 6 > 150){
				$("#responesParametersMsg").height($("#reponseParametersTable").height() - 6);
			}else{
				$("#responesParametersMsg").height(150);
				/*$('.datagrid-wrap').height(150)*/
				$('.datagrid-wrap').css('border','none');
			}
		
		}
}

function showIfDetial(){
	var urlParamObj = getParamobjFromUrl();
	var interfaceId = urlParamObj.interfaceId;
	var interfaceName = urlParamObj.interfaceName;
	if(interfaceId!=null){
		
		$.ajax({
			url : BASE_URL_HTTP_INTERFACE + '/findIfByIdForServiceScan' + '?id=' + window.decodeURI(interfaceId) + '&v=' + Math.random(),
			dataType : 'json',
			type : 'get',
// contentType : "application/json",
			success : function(data) {
				if(data.backValue == true){
					$("#systemName").val(window.decodeURI(interfaceName));
					setTimeout(function(){
						$("#searchNode").click();
					}, 500);
					
					FormEcho(data);
				}else if(data.backValue == false){
					$.messager.alert("错误","<p>没有找到对应的接口！ </p>","error");
				}else{
					$.messager.alert("错误","<p>没有找到对应的接口！ </p>","error");
				}
				
			},
			error : function() {
				$.messager
						.alert(
								"错误",
								"<p>服务异常，查询接口信息失败，请重新登录或稍后再试！ </p>",
								"error");
			}

		});
	}
}


function changeNodeClass(nodelist, start, end) {
	if(start < nodelist.length)
	{
		for(var i = start; i <= end; i++)
		{
			var node = nodelist[i];
			if(node.nodeType == "fieldSystem" && node.hasChildren && (!node.children || node.children.length == 0) && $(node.target).find(".tree-fieldSys").length == 0 )
			{
				$(node.target).find("span.tree-icon").prev().remove();
				$(node.target).children(".tree-icon.tree-file").before('<span class="tree-fieldSys tree-collapsed" data-ifIds="' + node.ifIds + '" data-id="' + node.id + '"></span>');
				$(node.target).children(".tree-fieldSys").click(function(){
					var $self = $(this);
					if($self.hasClass('tree-collapsed'))
					{//alert(node.id+'  '+node.text);													
						$self.removeClass('tree-collapsed').addClass('tree-expanded');
						//$('#tt').tree('expend', $self.parent()[0])
						jsonData = {
								systemId:$self.attr("data-id"),
								ifIds:$self.attr("data-ifIds")
						}
						$.ajax({
							url :BASE_URL_TREE+ '/getHttpBySystemIdForScan',
							dataType : 'json',
							type : 'post',
							data:jsonData,
							success : function(data){
								//alert(data)
								$('#tt').tree('append',{
									parent: $self.parent()[0],
									data: data
								});
							}
						}); 
					}
					else
					{
						$self.addClass('tree-collapsed').removeClass('tree-expanded');
						$('#tt').tree('collapse', $self.parent()[0]);
					}
					
				});
			}
			var icons = $(node.target).find("span.tree-icon");
			if (node.nodeType == 'systemInterface') {
				//var icons = $(node.target).find("span.tree-icon");
				if(node.interfaceType=='1'){
					$(icons[0]).removeClass("tree-file");
					$(icons[0]).addClass("icons4WebService");
				}
				else if(node.interfaceType=='2'){
					$(icons[0]).removeClass("tree-file");
					$(icons[0]).addClass("icons4Rest");
				}
				else if(node.interfaceType=='3'){
					$(icons[0]).removeClass("tree-file");
					$(icons[0]).addClass("icons4Ftp");
				}
			}
		}
		if(end + 1 < nodelist.length)
		{
			start = end + 1;
			end += 100;
			end = end > nodelist.length - 1? nodelist.length - 1:end;
			setTimeout(function(){
				changeNodeClass(nodelist, start, end);
			}, 50);
		}
	}
}


